<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>
	<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
	<title>优化代码---减少参数</title>
	<style type="text/css">
        #div1{
        	width:150px;height:150px;background: green;position: absolute;left:-150px;
        }
        #div1 span{
        	width:20px;height:50px;background:pink;position: absolute;top:50px;right:-20px;
        }
	</style>
	<script type="text/javascript">
        window.onload = function(){
            var oDiv = document.getElementById('div1');

            //当鼠标移入div1上时，显示div1
            oDiv.onmouseover = function(){
            	startMove(0);  //这里只要传入目标参数
            }

            //当鼠标移出div1上时，隐藏div1
            oDiv.onmouseout = function(){
            	startMove(-150);
            }

        }

        var timer = null;
        //运动框架  iTarget:目标
        function startMove(iTarget){
        	var oDiv = document.getElementById('div1');
        	//先清空所有定时器，保证重新开启时只有一个定时器在运行
        	clearInterval(timer);

            
            //动态判断需要传入的speed方向
            var speed = 0;  //初始化
            if(oDiv.offsetLeft>iTarget){
                speed = -10;
            }else{
                speed = 10;
            }


        	timer = setInterval(function(){
                if(oDiv.offsetLeft==iTarget){
                	clearInterval(timer);              	
                }else{
                	oDiv.style.left = oDiv.offsetLeft+speed+'px';
                }
        	}, 30);
        }
	</script>
</head>
<body>

    <div id="div1">
   	   <span>分享</span>
    </div>
	
</body>
</html>